<template>
  <div>
    <el-tree
      ref="tree"
      :data="data"
      show-checkbox
      default-expand-all
      node-key="id"
      highlight-current
      :props="defaultProps"
      @check="handleChange"
    />
  </div>
</template>
<script>
export default {
  props: {
    value: {
      type: String,
      default: () => ''
    },
    data: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  watch: {
    // 数据回显
    value: {
      immediate: true,
      handler(val) {
        val.split(',').forEach(value => {
          this.$nextTick(() => {
            this.$refs.tree.setChecked(value, true, false)
          })
        })
      }
    }
  },
  methods: {
    handleChange() {
      const roles = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys())
      this.$emit('input', roles.toString())
    }
  }
}
</script>
